#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/28 20:06
# file: scope.py
# author: lotus163

from backend.schemas import SysUserSch
from backend.schemas.system.scope import DataScopeSch
from backend.service.system.menu import MenuService
from backend.service.system.role_menu import RoleMenuService
from backend.service.system.user import UserService


class DataScopeService:

    async def get_scope_sch(self,user_all_sch:SysUserSch)->DataScopeSch:
        """ 计算数据权限 """
        # 角色的部门
        roles_depts_ids_list = []
        for role in user_all_sch.roles:
            roles_depts_ids_list.extend(role.deptIds)
        roles_depts_ids = list(set(roles_depts_ids_list))
        # 角色的菜单
        roles_menus_ids = await RoleMenuService().get_menu_ids_by_role_ids(user_all_sch.roleIds)
        # 角色的部门的用户
        roles_depts_users_ids = await UserService().get_user_ids_by_dept_ids(roles_depts_ids)
        # 文字权限
        if user_all_sch.admin:
            permissions = ["*:*:*"]
        else:
            permissions = await MenuService().get_permissions_list_by_menu_ids(roles_menus_ids)
        # 返回
        return DataScopeSch(user_id = user_all_sch.userId,
                            admin = user_all_sch.admin,
                            user_dept_id = user_all_sch.deptId,
                            user_roles_ids=user_all_sch.roleIds,
                            user_post_ids = user_all_sch.postIds,
                            roles_depts_ids = roles_depts_ids,
                            roles_menus_ids = roles_menus_ids,
                            roles_depts_users_ids = roles_depts_users_ids,
                            permissions = permissions)


